package com.masterclient.app.businessmodule.usermodule.userinfo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.usermodule.userinfo.contract.UpdateMobileContract;
import com.masterclient.app.businessmodule.usermodule.userinfo.contract.UpdateMobilePresenter;
import com.masterclient.app.utils.CaptchaUtil;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.Information;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = FCRouterPath.USER_CHECK_MOBILE)
public class CheckMobileActivity extends FCBusinessActivity<UpdateMobilePresenter> implements UpdateMobileContract.View {

    @BindView(R.id.mobile_old_txt)
    TextView mobile_old_txt;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.tv_get_yan)
    TextView tv_get_yan;
    @BindView(R.id.et_verify)
    EditText et_verify;
    @BindView(R.id.contact_service)
    View contact_service;

    @Autowired(name = "old_mobile_str")
    String old_mobile_str;


    CaptchaUtil captchaUtil;

    String action = "closeCheckMobileActivity";

    private BroadcastReceiver mBoradcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(action)) {
                finish();
            }
        }
    };

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_check_mobile;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("修改手机号");
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        mobile_old_txt.setText(old_mobile_str);
        add_listener();
        IntentFilter filter = new IntentFilter();
        filter.addAction(action);//为BroadcastReceiver指定一个action，即要监听的消息名字
        registerReceiver(mBoradcastReceiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        captchaUtil = new CaptchaUtil(CheckMobileActivity.this,"修改手机号");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                canCaptcha = false;
                mPresenter.getCaptcha(old_mobile_str, "change_mobile", ne);
            }

            @Override
            public void onFailed() {
canCaptcha = true;
            }
        });
    }

    private void add_listener() {
        et_verify.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if(charSequence.toString().trim().length() > 0){
                    next.setBackgroundResource(R.drawable.bg_rect_buy_black);
                    next.setTextColor(Color.parseColor("#FFFFFF"));
                }else{
                    next.setBackgroundResource(R.drawable.bankcard_bind_unable_click_bkg);
                    next.setTextColor(Color.parseColor("#FFFFFF"));
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @OnClick({R.id.next,R.id.tv_get_yan,R.id.contact_service}) void onClick(View view){
        switch (view.getId()){
            case R.id.next:
                String verify_str = et_verify.getText().toString().trim();
                if(!TextUtils.isEmpty(verify_str) && verify_str.length() > 0){
                    mPresenter.check_old_mobile(old_mobile_str,verify_str);
                }else{
                    showToast("请输入验证码");
                }
                break;
            case R.id.tv_get_yan:
                if(!canCaptcha){
                    return;
                }
                if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
                        mPresenter.getCaptcha(old_mobile_str, "change_mobile", "");
                    }else {
                        captchaUtil.start();
                    }
                } else {
                    canCaptcha = false;
                    mPresenter.getCaptcha(old_mobile_str, "change_mobile", "");
                }
                break;
            case R.id.contact_service:
                Information info = SobotManager.getBaseInfo();
                SobotApi.setChatTitleDisplayMode(CheckMobileActivity.this, SobotChatTitleDisplayMode.Default, "");
                SobotApi.startSobotChat(CheckMobileActivity.this, info);
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void check_old_mobile_result(String state, String msg) {

        if("1".equals(state)){
            ARouter.getInstance().build(AroutePath.PERSONAL_UPDATE_MOBILE).withString("old_mobile_str",old_mobile_str).navigation(this,100);
        }else{
            showToast(msg);
        }

    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        finish();
    }

    @Override
    public void mobiel_change_result(String state, String msg) {

    }

    CountDownTimer timer;
    boolean canCaptcha = true;
    @Override
    public void getCaptchaSuccess() {
        //tv_get_yan.setBackgroundResource(R.drawable.bg_gray_coner);
        tv_get_yan.setTextColor(0xffc1c1c1);
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_get_yan.setText(millisUntilFinished / 1000 + "s");
                tv_get_yan.setTextColor(0x4d000000);
                //tv_get_yan.setBackgroundResource(R.drawable.withdraw_get_code_bkg);
            }

            @Override
            public void onFinish() {
                canCaptcha = true;
                tv_get_yan.setTextColor(0xff7399E5);
                tv_get_yan.setBackground(null);
                tv_get_yan.setText("获取验证码");
            }
        };
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null){
            timer.cancel();
            timer = null;
        }
        unregisterReceiver(mBoradcastReceiver);
    }

    @Override
    public void getCaptchaFailed() {
        canCaptcha = true;
    }

    @Override
    public void getCaptchaFailed(String msg) {
        canCaptcha = true;
        showToast(msg);
    }

}
